package com.yuan.security;


import com.yuan.ayuancity.controller.common.CaptchaController;
import com.yuan.view.YuancityView;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class VerifyCodeFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {

        // 登录接口
        if (request.getRequestURI().contains("city/admin/login")
         ||request.getRequestURI().contains("/city/user/login")) {
            verifyCode(request, response, filterChain);
        } else {
            filterChain.doFilter(request, response);
        }

    }

    private void verifyCode(HttpServletRequest request,
                            HttpServletResponse response,
                            FilterChain filterChain) throws ServletException, IOException {

        HttpSession session = request.getSession();
        Object codeInSession = session.getAttribute(CaptchaController.VERIFY_CODE_IN_SESSION_KEY);

        String code = request.getParameter(CaptchaController.REQUEST_VERIFY_CODE_PARAMETER);

        if (codeInSession == null || code == null) {
            YuancityView.failure("非法请求...").responseWebClient(response);
        } else if (!codeInSession.toString().toLowerCase().equals(code.toLowerCase())) {
            session.removeAttribute(CaptchaController.VERIFY_CODE_IN_SESSION_KEY);
            YuancityView.failure("验证码不正确...",410).responseWebClient(response);
        } else {
            filterChain.doFilter(request, response);
        }
    }
}